package com.linqi.freebie.utils

import com.linqi.freebie.config.DepotInfo

object DepotParser {


    /**
     * 解析 key.vdf 文件内容，返回 DepotInfo 列表
     */
    fun parseKeyFile(content: ByteArray): List<DepotInfo> {
        return try {
            val text = content.toString(Charsets.UTF_8)
            val vdfMap = parseVdf(text)
            val depots = vdfMap["depots"] as? Map<String, Map<String, String>> ?: return emptyList()

            depots.mapNotNull { (dId, dInfo) ->
                val key = dInfo["DecryptionKey"]
                if (key != null) DepotInfo(dId, key) else null
            }
        } catch (e: Exception) {
            emptyList()
        }
    }

    /**
     * 解析 .manifest 文件名，返回 Pair<depotId, manifestId>
     */
    fun parseManifestFilename(filename: String): Pair<String?, String?> {
        if (!filename.endsWith(".manifest")) return null to null

        val name = filename.removeSuffix(".manifest")
        if (!name.contains("_")) return null to null

        val parts = name.split("_", limit = 2)
        if (parts.size != 2 || parts.any { !it.all(Char::isDigit) }) {
            return null to null
        }

        return parts[0] to parts[1]
    }

    /**
     * 简单解析 VDF 格式，只提取 depots 和 DecryptionKey
     */
    private fun parseVdf(vdfText: String): Map<String, Any> {
        val result = mutableMapOf<String, MutableMap<String, String>>()
        var currentDepot: String? = null
        val regexDepot = "\"(\\d+)\"".toRegex()
        val regexKey = "\"DecryptionKey\"\\s+\"([^\"]+)\"".toRegex()

        vdfText.lineSequence().forEach { line ->
            val depotMatch = regexDepot.find(line)
            if (depotMatch != null) {
                currentDepot = depotMatch.groupValues[1]
                result[currentDepot!!] = mutableMapOf()
            }

            val keyMatch = regexKey.find(line)
            if (keyMatch != null && currentDepot != null) {
                result[currentDepot]?.set("DecryptionKey", keyMatch.groupValues[1])
            }
        }

        return mapOf("depots" to result)
    }
}
